from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import jinja2
import models
from main import DEBUG, Handler, template_env, memcache_get, cache_control


class MetricHandler(Handler):

    """Base class for displaying a metric."""

    @cache_control
    @memcache_get
    def get(self):
        title = self.metric_property.replace('_', ' ')
        sort_order = '-' + self.metric_property
        query = models.Project.all().order(sort_order).fetch(50)
        projects_list = list(query)
        conversion_count = sum(1 if x.py3k_support else 0
                                    for x in projects_list)
        conversion_percentage = int(round(float(conversion_count) /
                                          (len(projects_list) or 1) * 100))
        template = template_env.get_template(self.template_name)
        self.response.out.write(template.render(projects=projects_list,
                                                metric=self.__class__.__doc__,
                                                title=title,
                                                converted=conversion_count,
                                            converted_pct=conversion_percentage))

class DownloadRateHandler(MetricHandler):

    """download rate for the latest release"""

    metric_property = 'download_rate'
    template_name = 'download_rate_metric.html'


class LargestDownloadsHandler(MetricHandler):

    """largest total downloads in any release"""

    metric_property = 'largest_downloads'
    template_name = 'largest_downloads_metric.html'


class LatestDownloadsHandler(MetricHandler):

    """most downloads for their latest release"""

    metric_property = 'latest_downloads'
    template_name = 'latest_downloads_metric.html'


class PollHandler(MetricHandler):

    """most votes on the Python 3 poll at http://www.python.org/"""

    metric_property = 'poll_count'
    template_name = 'poll_metric.html'


urls = [('/metrics/largest_downloads', LargestDownloadsHandler),
        ('/metrics/latest_downloads', LatestDownloadsHandler),
        ('/metrics/download_rate', DownloadRateHandler),
        ('/metrics/poll_count', PollHandler),
       ]

def application():
    return webapp.WSGIApplication(urls, debug=DEBUG)

def main():
    util.run_wsgi_app(application())


if __name__ == '__main__':
    main()
